<template>
  <div class="flex w-full">
    <!-- 聊天列表 -->
    <div class="message-left" :class="{ 'style-layoutkit': arrowRight }">
      <!-- 搜索框 -->
      <!-- <Search :class="{ 'opacity-0': arrowRight }" /> -->
      <div class="rght-setting">
        <svg-icon
          iconClass="mail_list"
          @click="showMessageBox"
          style="padding-top: 3px; font-size: 20px; margin-top: 1px"
        ></svg-icon>
        <el-icon @click="showSetting"><Setting /></el-icon>
      </div>
      <!-- tabs切换 -->
      <el-tabs
        v-model="activeName"
        class="demo-tabs"
        :class="{ 'opacity-0': arrowRight }"
        @tab-click="handleClick"
      >
        <!-- <el-tab-pane :label="$t('chat.whole')" name="whole"></el-tab-pane> -->
        <el-tab-pane label="我的" name="groupChat"></el-tab-pane>
        <!-- <el-tab-pane :label="unread" name="unread"></el-tab-pane> -->
        <el-tab-pane :label="$t('chat.mention')" name="mention"></el-tab-pane>
      </el-tabs>

      <div class="scroll-container" :class="{ 'style-net': !networkStatus }">
        <!-- 连接已断开 -->
        <networklink :show="!networkStatus" />
        <!-- 会话列表 -->
        <ConversationList ref="ConversationListRef" @handleConvListClick="handleConvListClick" />
      </div>
      <div class="layoutkit-center">
        <div @click="onRight(arrowRight)">
          <el-icon> <ArrowRight v-if="arrowRight" /><ArrowLeft v-else /> </el-icon>
        </div>
      </div>
    </div>
    <!-- 聊天框 -->
    <div class="message-right" :class="{ 'style-full': arrowRight }" id="svgBox">
      <EmptyMessage classNmae="empty" v-if="!conver" />
      <Header @showQuick="showQuick" />
      <!-- 聊天窗口 -->
      <Chatwin ref="chatRef" :class="{ 'style-h-full': fullScreen }" />
      <!-- 消息回复框 -->
      <ReplyBox />
      <div
        id="svgResize"
        :class="{ 'resize-hover': !fullScreen }"
        @mouseover="dragControllerDiv(chatRef)"
        v-if="showMsgBox"
      ></div>
      <!-- 多选框 -->
      <MultiChoiceBox />
      <!-- 编辑器 -->
      <Editors :detailItem="sessionDetailObj" :isniming="activeName == 'mention'" />
    </div>
    <RightUserInfo :userid="sessionDetailObj.userId" />
    <!-- 合并消息弹框 -->
    <MergeMessagePopup />
    <!-- 群详情 -->
    <GroupDetails
      v-if="isGroupChat"
      :groupProfile="conver.groupProfile"
      :staff="isallStaff(conver)"
    />

    <!-- 人员等待弹窗 -->
    <el-dialog v-model="showMessageVisible" title="查看访客" width="680" v-loading="loading">
      <el-tabs v-model="dialogActiveName" class="demo-tabs" @tab-click="handletabdialogClick">
        <el-tab-pane label="访客" name="0"></el-tab-pane>
        <el-tab-pane label="排队" name="1"></el-tab-pane>
      </el-tabs>
      <!-- 访客 -->
      <div v-if="dialogActiveName == '0'">
        <div class="search-bar">
          <el-form inline style="padding: 10px">
            <el-form-item label="区域">
              <el-cascader
                :options="regions"
                :props="{ multiple: true }"
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                clearable
                placeholder="请选择区域"
                @change="handleChangeCascader"
              />
            </el-form-item>
            <el-form-item label="设备">
              <el-cascader
                :options="devices"
                :props="{ multiple: true }"
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                clearable
                placeholder="请选择设备"
                @change="handleChangedevicesCascader"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getFetchVisitors">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="online-count">在线访问数: {{ onlineCount }}</div>
        <el-table :data="visitors" style="width: 100%" height="300">
          <el-table-column prop="name" label="访客信息" />
          <!-- <el-table-column prop="not_match_count" label="访问次数" /> -->
          <el-table-column prop="region" label="区域" />
          <el-table-column prop="device" label="设备" />
          <el-table-column prop="source" label="来源" />
          <!-- <el-table-column label="正在访问" scoped-slot="scope" v-slot="{ row }">
            <el-link :href="row.currentVisitUrl" target="_blank">查看</el-link>
          </el-table-column> -->
          <!-- <el-table-column label="操作" prop="options"> </el-table-column> -->
        </el-table>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchParams.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="searchParams.limit"
          layout=" sizes, prev, pager, next, jumper"
          :total="total"
          style="padding-top: 10px"
        ></el-pagination>
      </div>
      <!-- 排队 -->
      <div v-else>
        <div class="online-count">排队数: {{ queueCount }}</div>
        <el-table :data="queueList" style="width: 100%" height="300">
          <el-table-column prop="sessionName" label="访客信息" />
          <!-- <el-table-column prop="not_match_count" label="访问次数" /> -->
          <el-table-column prop="source" label="来源" />
          <el-table-column label="操作" prop="options">
            排队中
            <!-- <template #default="scope">
              <el-button type="text">{{ toonversition(scope.row.sessionId) }}</el-button>
            </template> -->
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="handleQueueSizeChange"
          @current-change="handleQueueCurrentChange"
          :current-page="searchParamsQueue.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="searchParamsQueue.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalQueue"
          style="padding-top: 10px"
        ></el-pagination>
      </div>
    </el-dialog>

    <!-- 客服会话 -->
    <el-dialog v-model="settingsVisible" title="客服设置" width="680">
      <el-tabs v-model="activeTab" @tab-click="handlekufuClick" v-loading="loading">
        <el-tab-pane label="客服欢迎语" name="greeting">
          <div>
            <h3>客户欢迎语</h3>
            <p>配置客服个人欢迎语后，在开启对话时将自动发送给顾客。</p>
            <div class="flex w-full">
              功能开启：
              <el-switch v-model="enabled" :active-value="true" :inactive-value="false"></el-switch>
            </div>

            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="editToolbarConfig"
              mode="simple"
            />
            <Editor
              class="editor-content"
              v-model="greeting"
              mode="simple"
              :defaultConfig="editorConfig"
              @onCreated="handleEditor"
              style="height: 300px"
            />
            <el-button type="primary" @click="saveGreeting">保存</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="客服名片" name="businessCard">
          <div class="flex w-full" style="padding: 10px">
            名片里面的信息将会被展示给对话中的客户
          </div>
          <el-form ref="cardForm" :model="cardInfo" label-width="100px">
            <el-form-item label="名称">
              <el-input v-model="cardInfo.nickname"></el-input>
            </el-form-item>
            <el-form-item label="自定义签名">
              <el-input v-model="cardInfo.signature"></el-input>
            </el-form-item>
            <el-form-item label="座机">
              <el-input v-model="cardInfo.tel"></el-input>
            </el-form-item>
            <el-form-item label="手机">
              <el-input v-model="cardInfo.mobile"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="cardInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="QQ">
              <el-input v-model="cardInfo.qq"></el-input>
            </el-form-item>
            <el-form-item label="WeChat">
              <el-input v-model="cardInfo.wechat"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveCardInfo">保存</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-drawer v-model="isShowQuick" title="选择快捷回复" direction="rtl" size="50%">
      <el-input
        v-model="filterText"
        style="width: 240px"
        placeholder="请输入需要检索的关键词"
        @keyup.enter="SearchTree"
      />
      <div v-loading="loading">
        <el-card style="margin: 10px 0">
          <h3>个人快捷回复</h3>
          <el-tree
            :data="personTree"
            class="filter-tree"
            node-key="id"
            ref="treeRef"
            :default-expand-all="true"
            @node-click="handleCheckTreeChange"
            :props="{ class: customNodeClass }"
            :filter-node-method="filterNode"
          />
        </el-card>
        <el-card style="margin: 10px 0">
          <h3>企业快捷回复</h3>

          <el-tree
            :data="companyTree"
            class="filter-tree"
            node-key="id"
            ref="treeCompanyRef"
            :default-expand-all="true"
            @node-click="handleCheckCompanyTreeChange"
            :props="{ class: customNodeClass }"
            :filter-node-method="filteCompanyrNode"
          />
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { $t } from "@/plugins/i18n";
import { useGetters, useState } from "@/utils/hooks/useMapper";
import emitter from "@/utils/mitt-bus";
import { useEventListener } from "@vueuse/core";
import storage from "@/utils/localforage/index";
import { USER_MODEL } from "@/constants/index";

import {
  onActivated,
  onDeactivated,
  onMounted,
  onUnmounted,
  ref,
  shallowRef,
  watchEffect,
  getCurrentInstance,
  onBeforeUnmount,
  nextTick,
} from "vue";

import { companyQuickReply, personQuickReply } from "@/api/node-admin-api/quickReply.js";
import { useStore } from "vuex";
import { dragControllerDiv, isallStaff } from "./utils/utils";
// import { Favico } from "pure-tools";

import Chatwin from "./chat/Chatwin.vue";
import ConversationList from "./chat/ConversationList.vue";
import Editors from "./chat/Editor.vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";

import GroupDetails from "./chat/GroupDetails.vue";
import EmptyMessage from "./components/EmptyMessage.vue";
import Header from "./components/Header.vue";
import MergeMessagePopup from "./components/MergeMessagePopup.vue";
import MultiChoiceBox from "./components/MultiChoiceBox.vue";
import ReplyBox from "./components/ReplyBox.vue";
import Search from "./components/Search.vue";
import networklink from "./components/networklink.vue";
import RightUserInfo from "./rightUserInfo.vue";
import {
  fetchVisitors,
  fetchQueue,
  getAllAreaList,
  getKefuGreetingSetting,
  SetKefuGreeting,
  getKefuInfo,
  setKefuInfo,
} from "@/api/node-admin-api/role.js";
import { placeholderMap } from "./utils/configure";
import { customAlert } from "./utils/utils";
import { getUserMessageBySessionId } from "@/api/node-admin-api/chat";
import { successMessage, warnMessage, errorMessage } from "@/utils/message";
const { currentConversation, currentReplyMsg } = useState({
  currentConversation: (state) => state.conversation.currentConversation,
  currentReplyMsg: (state) => state.conversation.currentReplyMsg,
});
import { sendChatMessage } from "./utils/utils";
const { isOwner, toAccount, currentType } = useGetters(["isOwner", "toAccount", "currentType"]);

const unread = ref("");
const loading = ref(false);
const chatRef = ref(null);
const activeName = ref("groupChat");
const ConversationListRef = ref(null);
const userid = ref(null); // 当前客户的id
const { dispatch, commit } = useStore();
// const favicon = new Favico({ animation: "none" });\
const { emit } = getCurrentInstance();

const editorConfig = ref({
  placeholder: "请输入内容...",
  EXTEND_CONF: {
    mentionConfig: {
      pinyinSearch: true,
    },
  },
});

const editToolbarConfig = ref({
  toolbarKeys: [
    "clearStyle",
    "divider",
    "emotion",
    "blockquote",
    "|",
    // 菜单组，包含多个菜单
    {
      key: "group-link",
      title: "链接",
      menuKeys: ["insertLink", "editLink", "unLink", "viewLink"],
    },

    "redo",
    "undo",
  ],
});

const { isGroupChat } = useGetters(["isGroupChat"]);
const { networkStatus, conver, showMsgBox, totalUnreadMsg, arrowRight, fullScreen } = useState({
  networkStatus: (state) => state.conversation.networkStatus,
  totalUnreadMsg: (state) => state.conversation.totalUnreadMsg,
  conver: (state) => state.conversation.currentConversation,
  showMsgBox: (state) => state.conversation.showMsgBox,
  arrowRight: (state) => state.settings.arrowRight,
  fullScreen: (state) => state.settings.fullScreen,
});

const showMessageVisible = ref(false);
const dialogActiveName = ref("0");
const total = ref(0);
const searchParams = ref({ areacodes: [], devices: [], page: 1, limit: 20 });
const totalQueue = ref(0);
const searchParamsQueue = ref({ page: 1, limit: 20 });
const regions = ref([]);
const devices = ref([
  {
    value: "desktop",
    label: "桌面",
    children: [
      { value: "windows", label: "Windows" },
      { value: "macos", label: "MacOS" },
    ],
  },
  {
    value: "mobile",
    label: "手机",
    children: [
      { value: "android", label: "Android" },
      { value: "ios", label: "iOS" },
    ],
  },
]);
const onlineCount = ref(0);
const queueCount = ref(0);
const visitors = ref([]);
const queueList = ref([]);

// 用户等待列表
const showMessageBox = () => {
  showMessageVisible.value = true;
  dialogActiveName.value = "0";
  getFetchVisitors();
  getReginsList();
};

const getFetchVisitors = () => {
  loading.value = true;
  fetchVisitors(searchParams.value)
    .then((res) => {
      if (res.code == 20000) {
        visitors.value = res.data.records;
        onlineCount.value = res.data.total;
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};
const handletabdialogClick = (val) => {
  dialogActiveName.value = val;
  if (val == "0") {
    getFetchVisitors();
    getReginsList();
  } else {
    getFetchQueue();
  }
};
const handleChangeCascader = (CascaderValue) => {
  let list = [];
  CascaderValue.map((item) => {
    const data = item[item.length - 1];
    list.push(data);
  });

  searchParams.value.areacodes = [...list];
};

const handleChangedevicesCascader = (cas) => {
  let list = [];
  cas.map((item) => {
    const data = item[item.length - 1];
    list.push(data);
  });

  searchParams.value.devices = [...list];
};

const getReginsList = () => {
  loading.value = true;
  getAllAreaList({ level: 2 })
    .then((res) => {
      if (res.code == 20000) {
        regions.value = transformListToCascaderOptions(res.data.list || []);
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const transformListToCascaderOptions = (list) => {
  return list.map((item) => ({
    value: item.areaCode,
    label: item.name,
    children:
      item.children && item.children.length > 0
        ? transformListToCascaderOptions(item.children)
        : [],
  }));
};

const handleCheckChange = (data, checked, indeterminate) => {
  if (checked) {
    searchParams.value.areacodes.push(data.id);
  } else {
    const index = searchParams.value.areacodes.findIndex((item) => item.id == data.id);
    if (index !== -1) {
      searchParams.value.areacodes.splice(index, 1);
    }
  }
};

const handleSizeChange = (newSize) => {
  searchParams.value.limit = newSize;
  fetchVisitors();
};

const handleCurrentChange = (newPage) => {
  searchParams.value.page = newPage;
  fetchVisitors();
};

const getFetchQueue = () => {
  loading.value = true;
  fetchQueue(searchParamsQueue.value)
    .then((res) => {
      if (res.code == 20000) {
        queueList.value = [...res.data.records] || [];
        queueCount.value = res.data.total;
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// TODO 根据 sessionid 找到会话，并且打开会话
const toonversition = (sessionid) => {};

const handleQueueSizeChange = (newSize) => {
  searchParamsQueue.value.limit = newSize;
  getFetchQueue();
};

const handleQueueCurrentChange = (newPage) => {
  searchParamsQueue.value.page = newPage;
  getFetchQueue();
};

// 设置客服会话
const editorRef = shallowRef(); // 编辑器实例，必须用 shallowRef
const editor = ref(null);
const toolbarConfig = ref({
  excludeKeys: [
    "headerSelect",
    "italic",
    "group-more-style", // 排除菜单组，写菜单组 key 的值即可
  ],
});
const settingsVisible = ref(false);
const activeTab = ref("greeting");
const enabled = ref(false);
const greetingText = ref("");
const greeting = ref(""); // 内容 HTML
const mode = "default"; // 'default' 或 'simple'
const cardInfo = ref({
  name: "",
  signature: "",
  landline: "",
  mobile: "",
  email: "",
  qq: "",
  wechat: "",
});
const onChange = (editor) => {
  const content = editor.children;
};
// 拖拽事件
const dropHandler = (event) => {
  customPaste(editorRef.value, event);
};
const handleEditor = (editor, created = true) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const customPaste = (editor, event, callback) => {
  console.log("ClipboardEvent 粘贴事件对象", event);
  // const text = event.clipboardData?.getData("text/plain"); // 获取粘贴的纯文本
  // https://developer.mozilla.org/zh-CN/docs/Web/API/DragEvent DragEvent 拖拽
  // https://developer.mozilla.org/zh-CN/docs/Web/API/ClipboardEvent ClipboardEvent 粘贴
  const items = event?.clipboardData?.items ?? event?.dataTransfer?.items;
  for (const item of items) {
    kindHandlers[item.kind]?.(item, editor);
  }
  event.preventDefault();
  callback?.(false);
};
const handlekufuClick = (val) => {
  activeTab.value = val;
  if (val == "greeting") {
    getKefuGreeting();
  } else {
    getKefu();
  }
};

const getKefu = () => {
  loading.value = true;
  const userInfo = storage.get(USER_MODEL);
  getKefuInfo({ userid: userInfo.user.userId })
    .then((res) => {
      if (res.code == 20000) {
        cardInfo.value = res.data.result;
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const saveGreeting = () => {
  loading.value = true;
  const params = {
    greeting: greeting.value,
    enabled: enabled.value,
  };
  SetKefuGreeting(params)
    .then((res) => {
      if (res.code == 20000) {
        successMessage("保存欢迎语成功！");
        settingsVisible.value = false;
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const saveCardInfo = () => {
  console.log("Saving card info:", cardInfo.value);

  setKefuInfo(cardInfo.value)
    .then((res) => {
      if (res.code == 20000) {
        successMessage("保存成功！");
        settingsVisible.value = false;
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const showSetting = () => {
  settingsVisible.value = true;
  getKefuGreeting();
};

const getKefuGreeting = () => {
  loading.value = true;
  const userInfo = storage.get(USER_MODEL);
  getKefuGreetingSetting({ userid: userInfo.user.userId })
    .then((res) => {
      if (res.code == 20000) {
        greeting.value = res.data.result.greeting;
        enabled.value = res.data.result.enabled;
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const fnTotalUnreadMsg = () => {
  const unreadCount = totalUnreadMsg.value;
  const isUnread = unreadCount > 0;
  const num = unreadCount > 99 ? "99+" : unreadCount;
  unread.value = isUnread ? `${$t("chat.unread")}(${num})` : $t("chat.unread");
  // isUnread ? favicon.badge(num) : favicon.reset();
};
const handleClick = ({ props }, event) => {
  const { label, name } = props;
  commit("TOGGLE_LIST", name);
};

//  置顶当前对话框
const handleClickMenuItem = (params) => {
  if (ConversationListRef.value) {
    ConversationListRef.value.handleClickMenuItem(params);
  }
};

const detailItem = ref({});
// 传递当前的置顶状态
const handleConvListClick = (params) => {
  userid.value = params.groupID;
  emit("handleConvListClick", params); // 传递当前的置顶状态
  detailItem.value = params;
  getuerInfo();
};

// 根据会话  ID 获取用户ID
const sessionDetailObj = ref({});
const getuerInfo = () => {
  const sessionId = detailItem.value.conversationID.split("GROUP")[1];
  getUserMessageBySessionId({ sessionId: sessionId }).then((res) => {
    if (res.code == 20000) {
      nextTick(() => {
        sessionDetailObj.value = res.data.detail;
      });
    }
  });
};

// 点击快捷回复
const isShowQuick = ref(false);
const companyTree = ref([]);
const personTree = ref([]);
const showQuick = () => {
  isShowQuick.value = true;
  getCompanyTree();
  getPersonTree();
};

// 获取企业的列表数据
const getCompanyTree = () => {
  loading.value = true;
  companyQuickReply()
    .then((res) => {
      if (res.code == 20000) {
        companyTree.value = transformData(res.data.list);
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};
// 获取个人的列表数据
const getPersonTree = () => {
  loading.value = true;
  personQuickReply()
    .then((res) => {
      if (res.code == 20000) {
        personTree.value = transformData(res.data.list);
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const handleCheckTreeChange = (data, node, treenode, event) => {
  toPushAnswer(data.answer);
  isShowQuick.value = false;
};
const handleCheckCompanyTreeChange = (data, node, treenode, event) => {
  toPushAnswer(data.answer);
  isShowQuick.value = false;
};

// watch(filterText, (val) => {
//   treeRef.value.filter(val);
//   treeCompanyRef.value.filter(val);
// });

const filterText = ref("");
const treeRef = ref(null);
const treeCompanyRef = ref(null);
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.includes(value.target.value);
};
const filteCompanyrNode = (value, data) => {
  if (!value) return true;
  return data.label.includes(value.target.value);
};

const SearchTree = (val) => {
  treeRef.value.filter(val);
  treeCompanyRef.value.filter(val);
};

const toPushAnswer = (anaswer) => {
  console.log("anaswer: ", anaswer);
  const data = sendMsgBefore(anaswer);
  console.log("data: ", data);

  const message = sendChatMessage(data);
  console.log("message: ", message);

  message.map((message) => {
    dispatch("SESSION_MESSAGE_SENDING", {
      payload: {
        convId: currentConversation.value.conversationID,
        message,
      },
    });
  });
};

const customNodeClass = (data, node) => {
  if (data.msgType == "question") {
    return "is-tree-link";
  }
  return null;
};

const searchTree = ref("");
const handleSearchTree = () => {};

// 格式转换为 tree 可用的结构
function transformData(data) {
  function transformNode(node) {
    return {
      id: node.id,
      label: node.name ? node.name : node.question,
      msgType: node.name ? "class" : "question",
      answer: node.answer ? node.answer : "",
      children: node.replys ? node.replys.map(transformNode) : [], // 递归转换所有子节点
    };
  }

  return data.map(transformNode);
}

const sendMsgBefore = (message) => {
  const text = message; // 纯文本内容
  return {
    convId: toAccount.value,
    convType: currentType.value,
    textMsg: message,
    reply: currentReplyMsg.value,
    isHave: Boolean(text),
  };
};

const onRight = (value) => {
  commit("UPDATE_USER_SETUP", { key: "arrowRight", value: !value });
};
useEventListener(window, "online", () => {
  commit("SET_NETWORK_STATUS", true);
});
useEventListener(window, "offline", () => {
  commit("SET_NETWORK_STATUS", false);
});
useEventListener(window, "focus", () => {
  if (!conver.value) return;
  commit("SET_HISTORYMESSAGE", {
    type: "MARKE_MESSAGE_AS_READED",
    payload: {
      convId: conver?.value.conversationID,
      message: conver.value,
    },
  });
});
onActivated(() => {
  emitter.emit("updataScroll");
  commit("TOGGLE_LIST", "groupChat");
  // if (ConversationListRef.value) {
  //   ConversationListRef.value.getAssignMyList();
  // }
});
onDeactivated(() => {});
onMounted(() => {
  commit("UPDATE_USER_SETUP", { key: "arrowRight", value: false });
});
defineExpose({ handleClickMenuItem });
onUnmounted(() => {});
watchEffect(() => {
  fnTotalUnreadMsg();
});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style lang="scss" scoped>
.rght-setting {
  display: inline-flex;
  align-items: center;
  justify-content: flex-end;
  position: absolute;
  right: 0;
  top: 6px;
  z-index: 999;
  .el-icon {
    font-size: 17px;
    cursor: pointer;
    color: black;
    margin: 5px 5px 0 5px;
    opacity: 0.9;
  }
}

.is-tree-link > .el-tree-node__content {
  color: var(--el-button-text-color);
}

:deep(.el-tree-node .is-tree-link) {
  color: var(--el-button-text-color);
  cursor: pointer;
}

.wangeditor {
  word-break: break-all;

  height: 300px;
  .editor-content {
    height: 300px;
    overflow-y: hidden;
    :deep(.w-e-text-container p) {
      margin: 0;
    }
    :deep(.w-e-image-dragger) {
      display: none;
    }
    :deep(.w-e-text-placeholder) {
      font-style: normal;
      font-size: 15px;
      top: 5px;
    }
    :deep(.w-e-selected-image-container) {
      overflow: visible;
    }
    :deep(.w-e-scroll) {
      @include scrollBar;
    }
  }
}
.online-count {
  font-size: 14px;
  color: var(--color-message-chat-name);
  padding: 12px;
}
.demo-tabs {
  user-select: none;
  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 16px;
  }
  :deep(.el-tabs__nav-wrap) {
    margin: 0;
  }
}
.message-left {
  width: 280px;
  position: relative;
  transition: width 0.2s cubic-bezier(0.215, 0.61, 0.355, 1);
}
.style-layoutkit {
  width: 0px;
}
.style-h-full {
  height: 0px !important;
  border-bottom: none;
}
.style-full {
  width: 100% !important;
}
.message-right {
  background: var(--color-body-bg);
  border-left: 1px solid var(--color-border-default);
  width: calc(100% - 280px);
  height: 100%;
  position: relative;
  overflow: hidden;
  min-width: 274px;
}
.scroll-container {
  height: calc(100% - 60px - 40px);
  position: relative;
}
.style-net {
  height: calc(100% - 60px - 34px - 40px);
}

#svgResize {
  position: absolute;
  height: 2.5px;
  z-index: 10;
  width: 100%;
  border-radius: 5px;
  transition: all 0.5s cubic-bezier(0.215, 0.61, 0.355, 1);
}
.resize-hover:hover {
  cursor: s-resize;
  background: #22222230;
}
.back-to-the-bottom {
  position: absolute;
  width: 70px;
  height: 20px;
  background: #17a7f6;
  top: -30px;
  right: 15px;
  z-index: 1;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  cursor: pointer;
}
.layoutkit-center {
  pointer-events: all;
  position: absolute;
  z-index: 1;
  display: flex;
  align-items: center;
  top: 0;
  right: -16px;
  width: 16px;
  height: 100%;
  display: flex;
  & > div {
    align-items: center;
    display: flex;
    width: 16px;
    height: 40px;
    border-radius: 0 4px 4px 0;
    pointer-events: all;
    cursor: pointer;
    color: #999999;
    background: rgba(0, 0, 0, 0.03);
    border-color: #e3e3e3;
    border-style: solid;
    border-width: 1px;
    display: none;
  }
  &:hover > div {
    display: flex !important;
  }
}
</style>
